package com.tianfei.crowd.mvc.config;

import com.tianfei.crowd.entity.Admin;
import com.tianfei.crowd.entity.Role;
import com.tianfei.crowd.service.api.AdminService;
import com.tianfei.crowd.service.api.AuthService;
import com.tianfei.crowd.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 自定义SpringSecurity数据库查询方式
 * UserDetailsService 实现类
 *
 * @author: Herz
 * @date: 2021/7/21 15:09
 */

@Component
public class CrowdUserDetailsService implements UserDetailsService {

    @Autowired
    AdminService adminService;

    @Autowired
    RoleService roleService;

    @Autowired
    AuthService authService;


    @Override
    public UserDetails loadUserByUsername(

            // 表单提交的用户名
            String userName) throws UsernameNotFoundException {

        // 1、根据 表单 提交的用户名 查询Admin对象
        Admin admin = adminService.getAdminByLoginAcct(userName);

        // 2、获取该Admin对象的用户id
        Integer adminId = admin.getId();

        // 3、根据 adminId 获取 角色信息
        List<Role> assignedRoles = roleService.getAssignedRole(adminId);


        // 4、根据 adminId 获取权限信息
        List<String> authNames = authService.getAssignedAuthNameByAdminId(adminId);


        // 5、创建集合对象来存储 GrantedAuthority
        List<GrantedAuthority> authorities = new ArrayList<>();

        // 6、遍历assignedRoles存入角色信息
        for (Role role : assignedRoles) {

            // 不要忘记添加前缀
            String roleName = "ROLE_" + role.getName();

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);

            authorities.add(simpleGrantedAuthority);
        }

        // 7、遍历 authNames 集合 存入权限信息
        for (String authName : authNames) {

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);

            authorities.add(simpleGrantedAuthority);
        }



        // 8、封装到 SecurityAdmin 对象中
        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);

        return securityAdmin;
    }
}
